<template>
	<view>
		<view class="flex text-center text-white text-lg bg">
			<view class="title_btn flex-sub bg" @click="cut(1)" :class="title_color==1?'bgCol2':''">我的余额
			</view>
			<view class="title_btn flex-sub bg" @click="cut(2)" :class="title_color==2?'bgCol2':''">我的收益
			</view>
		</view>
		<view v-if="title_color==1" class="padding">
			<view class=" radius bg">
				<view class=" u-flex u-p-l-30 u-p-t-30 u-p-b-30">
					<view class="u-m-r-20">
						<u-avatar :src="avatar" size="80"></u-avatar>
					</view>
					<view class="u-flex-1 ">
						<view class="u-font-16 text-white text-bold">{{money}}元</view>
						<view class="u-font-12 u-m-t-10" style="color: #999999;">用于平台支付</view>
					</view>
				</view>
			</view>
			<view class="margin-top radius bg flex justify-between flex-wrap padding-lr padding-bottom">
				<view v-for="(item,index) in wallet" :key='index'
					class="flex justify-between padding-sm radius margin-top"
					style="color: #1E1F31;background-color: #F7F7F7; width: 46%;" @click="active(item)"
					:class="{active:item.isSelect}">
					<view>
						¥{{item.price}}
					</view>
				</view>
			</view>

			<view class="bg margin-top padding-lr radius">
				<view>
					<view style="display: flex;height: 100upx;align-items: center;padding: 20upx 0;"
						v-for="(item,index) in openLists" :key='index'>
						<image :src="item.image" style="width: 55upx;height: 55upx;border-radius: 50upx;"></image>
						<view style="font-size: 30upx;margin-left: 20upx;width: 70%;">{{item.text}}
						</view>
						<radio-group name="openWay" style="margin-left: 20upx;" @tap='selectWay(item)'>
							<label class="tui-radio">
								<radio color="#1789FD" :checked="openWay === item.id ? true : false" />
							</label>
						</radio-group>
					</view>
				</view>
			</view>

			<view class="btn" @click="pay">确认支付</view>
		</view>
		<view v-if="title_color==2" class="padding">
			<view class="bg radius text-white padding">
				<view class="text-lg">可用余额</view>
				<view class="flex margin-top-sm">
					<!-- <view class="text-xxl"></view> -->
					<view class="text-xxl">{{money}}元</view>
				</view>
			</view>
			<view class="bg radius text-white padding margin-top">
				<view class="text-lg margin-bottom">提现金额</view>
				<input type="text" placeholder="请输入提现金额" v-model="moneyNum">
			</view>
			<view class=" text-grey margin-top">{{placeholder}}</view>

			<view class="bg margin-top padding-lr radius">
				<view>
					<view class="flex align-center justify-between padding-lr-sm" style="height: 100upx;"
						v-for="(item,index) in openList" :key='index'>
						<image :src="item.image" style="width: 55upx;height: 55upx;border-radius: 50upx;"></image>
						<view style="font-size: 30upx;margin-left: 20upx;width: 70%;">{{item.text}}
						</view>
						<radio-group name="opentype" style="margin-left: 20upx;" @tap='selectWay1(item)'>
							<label class="tui-radio">
								<radio color="#1789FD" :checked="opentype === item.id ? true : false" />
							</label>
						</radio-group>
					</view>
				</view>
			</view>

			<view class="btn" @click="cashMoney">立即提现</view>
		</view>


		<view class="flex justify-around margin-top text-white">
			<view @click="goNav('/my/wallet/zhifubao')" v-if="checkZFB != '否'">提现账号</view>
			<view @click="goNav('/my/wallet/mymoneydetail')">钱包明细</view>
			<view @click="isShow">微信收款码</view>
			<view @click="goNav('/my/wallet/cashList')">提现记录</view>
		</view>

		<!-- 微信收款码弹框 -->
		<u-popup v-model="show" mode="center">
			<view class="padding">
				<view class="text-center text-lg text-bold flex justify-between">
					<view></view>
					<view>添加微信收款码</view>
					<view @click="show=false">X</view>
				</view>
				<!-- <view class="text-center padding-top-sm padding-bottom-lg" style="color: #999999;">请提交微信号和微信二维码
				</view> -->
				<view style="width: 80%;margin: 0 auto;">
					<view class="margin-top" @click.stop="weixin"
						style="border: 4rpx solid #010101;border-radius: 16rpx;overflow: hidden;">
						<!-- <image src="../../static/images/my/erweima.png" v-if="!wximg"></image> -->
						<image :src="wxImg?wxImg:'../../static/images/my/erweima.png'" mode=""></image>
					</view>
				</view>
				<!-- <view class="text-center margin-top-sm " @click="submit"
					style="border-radius: 10rpx;background-color: #7E59FF;color: #fff;height: 80rpx;line-height: 80rpx;">保存</view> -->
			</view>
		</u-popup>
	</view>
</template>

<script>
	import configdata from '@/common/config.js';
	export default {
		data() {
			return {
				show: false,
				title_color: 1,
				money: 0,
				avatar: '',
				Profit: 0,
				openLists: [{
					image: '../static/zhifubao.png',
					text: '支付宝',
					id: 1
				}, {
					image: '../static/icon_weixin.png',
					text: '微信',
					id: 2
				}],
				checkZFB: '否',
				openWay: 1,
				wallet: [],
				moneyNum: null,
				thisSelect: {},
				charge: 0, //提现手续费
				maxMoney: 0, //最高提现额度
				minMoney: 0, //最低提现额度
				ratio: '', //金元比例
				placeholder: '',
				sp: 0,
				openList: [{
					image: '../static/zhifubao.png',
					text: '支付宝',
					id: 1
				}, {
					image: '../static/icon_weixin.png',
					text: '微信',
					id: 2
				}],
				opentype: 1,
				wxImg: '',
				WxTXFangShi: 1
			}
		},
		onLoad() {
			this.avatar = uni.getStorageSync('avatar')


			// #ifdef APP-PLUS
			this.openLists = [{
				image: '../../static/images/my/zhifubao.png',
				text: '支付宝',
				id: 1
			}, {
				image: '../../static/images/my/icon_weixin.png',
				text: '微信',
				id: 2
			}];
			this.openWay = 1;
			// #endif

			// #ifdef MP-WEIXIN
			this.openLists = [{
				image: '../../static/share/icon_weixin.png',
				text: '微信',
				id: 2
			}];
			this.openWay = 2;
			// #endif

			// #ifdef H5
			let ua = navigator.userAgent.toLowerCase();
			if (ua.indexOf('micromessenger') !== -1) {
				//公众号是否自动登录  237
				this.$Request.get('/app/common/type/237').then(res => {
					if (res.data && res.data.value && res.data.value == '是') {
						this.openLists = [{
							image: '../../static/images/my/zhifubao.png',
							text: '支付宝',
							id: 1
						}, {
							image: '../../static/images/my/icon_weixin.png',
							text: '微信',
							id: 2
						}];
						this.openWay = 2;
					} else {
						this.openLists = [{
							image: '../../static/images/my/zhifubao.png',
							text: '支付宝',
							id: 1
						}];
						this.openWay = 1;
					}
				})
			}
			// #endif

			this.$Request.getT('/app/common/type/244').then(res => {
				if (res.code == 0) {
					if (res.data && res.data.value) {
						this.WxTXFangShi = res.data.value;
					}
				}
			});

			this.$Request.getT('/app/common/type/245').then(res => {
				if (res.code == 0) {
					if (res.data && res.data.value) {
						this.checkZFB = res.data.value;
						if (res.data.value === '否') {
							this.openList = [{
								image: '../static/icon_weixin.png',
								text: '微信',
								id: 2
							}];
							this.opentype = 2;
						}
					}
				}
			});

		},
		onShow() {
			this.getMoneyType()
			this.getMoney()
			this.getCharge()
			this.getMinMoney()
			this.getMaxMoney()
			this.getRatio()
			this.getUserInfo()
		},
		methods: {
			active(e) {
				this.wallet.forEach(res => {
					if (res.id == e.id) {
						res.isSelect = true
						this.thisSelect = e
					} else {
						res.isSelect = false
					}
				})
			},
			getMoneyType() {
				this.$Request.getT('/app/common/type/619').then(res => {
					if (res.code == 0 && res.data && res.data.value) {
						let money = res.data.value.split(',')
						let arr = []
						money.forEach((item, index) => {
							let data = {}
							data.id = index
							data.price = item,
								data.isSelect = false
							arr.push(data)
						})
						this.wallet = arr
						this.thisSelect = arr[0]
						this.thisSelect.isSelect = true
					}
				});
			},
			//用户收款码弹框
			isShow() {
				// this.getUserInfo()
				this.show = true
			},
			getUserInfo() {
				this.$Request.get("/app/user/selectUserById").then(res => {
					if (res.code == 0) {
						this.avatar = res.data.avatar ? res.data.avatar : '../../static/logo.png'
						uni.setStorageSync('avatar', res.data.avatar)
						this.wxImg = res.data.wxImg
						console.log(this.wxImg, '00000')
					}
				});
			},
			// 提现手续费
			getCharge() {
				this.$Request.get("/app/common/type/152").then(res => {
					if (res.code == 0) {
						this.charge = res.data.value
						this.placeholder = '手续费:' + this.charge * 100 + '%' + ',最低提现:' +
							this.minMoney * 1 + ',最高提现:' + this.maxMoney * 1
					}
				});
			},
			// 最低提现额度
			getMinMoney() {
				this.$Request.get("/app/common/type/112").then(res => {
					if (res.code == 0) {
						this.minMoney = res.data.value
						this.placeholder = '服务费:' + this.charge * 100 + '%' + ',最低提现:' +
							this.minMoney * 1 + ',最高提现:' + this.maxMoney * 1
					}
				});
			},
			// 最高提现额度
			getMaxMoney() {
				this.$Request.get("/app/common/type/153").then(res => {
					if (res.code == 0) {
						this.maxMoney = res.data.value
						this.placeholder = '服务费:' + this.charge * 100 + '%' + ',最低提现:' +
							this.minMoney * 1 + ',最高提现:' + this.maxMoney * 1
					}
				});
			},
			// 金元比例
			getRatio() {
				this.$Request.get("/app/common/type/154").then(res => {
					if (res.code == 0) {
						this.ratio = res.data.value
						this.placeholder = '服务费:' + this.charge * 100 + '%' + ',最低提现:' +
							this.minMoney * 1 + ',最高提现:' + this.maxMoney * 1
						this.wallet.forEach(re => {
							re.num = re.price * res.data.value
						})
					}
				});
			},
			cut(e) {
				this.title_color = e
			},
			goNav(url) {
				uni.navigateTo({
					url
				})
			},

			// 我的余额
			getMoney() {
				this.$Request.get("/app/userMoney/selectMyMoney").then(res => {
					if (res.code == 0 && res.data) {
						console.log(res.data.money)
						this.money = res.data.money
					}
				});
			},
			selectWay: function(item) {
				this.openWay = item.id;
			},
			pay() {
				let data = {
					money: this.thisSelect.price
				}
				console.log(data)
				// 获取订单编号
				this.$Request.post("/app/appOrder/insertOrder", data).then(res => {
					console.log(res, '********')
					uni.showLoading({
						title: '支付中...'
					});
					if (res.code == 0) {
						// this.Profit = res.data
						if (this.openWay == 2) {
							// #ifdef APP-PLUS
							// 微信APP支付 根据订单id获取支付信息
							this.$Request.post("/app/wxPay/payAppOrder", {
								id: res.data.id
							}).then(ret => {
								this.isCheckPay(ret.code, 'wxpay', JSON.stringify(ret.data));
							});
							// #endif

							// #ifdef MP-WEIXIN
							// 微信小程序支付
							this.$Request.post('/app/wxPay/wxPayJsApiOrder', {
								orderId: res.data.id
							}).then(ret => {
								uni.hideLoading()
								uni.requestPayment({
									provider: 'wxpay',
									timeStamp: ret.data.timestamp,
									nonceStr: ret.data.noncestr,
									package: ret.data.package,
									signType: ret.data.signType,
									paySign: ret.data.sign,
									success: function(suc) {
										console.log('success:' + JSON.stringify(suc));
										uni.showToast({
											title: '支付成功',
											icon: 'success'
										})
										setTimeout(d => {
											uni.navigateBack(1)
										}, 1000);
									},
									fail: function(err) {
										console.log('fail:' + JSON.stringify(err));
										uni.showToast({
											title: '支付失败',
											icon: 'none'
										})
									}
								});
							});
							// #endif

							// #ifdef H5
							let ua = navigator.userAgent.toLowerCase();
							if (ua.indexOf('micromessenger') !== -1) {
								this.$Request.post('/app/wxPay/wxPayMpOrder?orderId=' + res.data.id).then(res => {
									if (res.code == 0) {
										this.callPay(res.data);
									} else {
										uni.showToast({
											icon: 'none',
											title: '支付失败!'
										});
									}
								});
							}
							// #endif

						} else {
							// #ifdef H5
							this.$Request.post('//app/aliPay/payMoneyOrder?orderId=' + res.data.id + '&classify=2')
								.then(
									res => {
										if (res.code === 0) {
											const div = document.createElement('div')
											div.innerHTML = res.data //此处form就是后台返回接收到的数据
											document.body.appendChild(div)
											document.forms[0].submit()
										} else {
											uni.showToast({
												icon: 'none',
												title: '支付失败!'
											});
										}
									});
							// #endif
							// #ifdef APP
							// APP支付宝支付
							this.$Request.post("/app/aliPay/payMoneyOrder", {
								orderId: res.data.id,
								classify: 1
							}).then(ret => {
								console.log(ret)
								this.isCheckPay(ret.code, 'alipay', ret.data);
							});
							// #endif

						}
					}
				});
			},
			callPay: function(response) {
				if (typeof WeixinJSBridge === "undefined") {
					if (document.addEventListener) {
						document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady(response), false);
					} else if (document.attachEvent) {
						document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady(response));
						document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady(response));
					}
				} else {
					this.onBridgeReady(response);
				}
			},
			onBridgeReady: function(response) {
				let that = this;
				if (!response.package) {
					return;
				}
				console.log(response, '++++++++')
				WeixinJSBridge.invoke(
					'getBrandWCPayRequest', {
						"appId": response.appid, //公众号名称，由商户传入
						"timeStamp": response.timestamp, //时间戳，自1970年以来的秒数
						"nonceStr": response.noncestr, //随机串
						"package": response.package,
						"signType": response.signType, //微信签名方式：
						"paySign": response.sign //微信签名
					},
					function(res) {
						console.log(res, '/*-/*-/*-')
						if (res.err_msg === "get_brand_wcpay_request:ok") {
							// 使用以上方式判断前端返回,微信团队郑重提示：
							//res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
							uni.showLoading({
								title: '支付成功'
							});
							setTimeout(function() {
								uni.hideLoading();
							}, 1000);
						} else {
							uni.hideLoading();
						}
						WeixinJSBridge.log(response.err_msg);
					}
				);
			},
			isCheckPay(status, name, order) {
				if (status == 0) {
					this.setPayment(name, order);
				} else {
					uni.hideLoading();
					uni.showToast({
						title: '支付信息有误',
						icon: 'none'
					});
				}
			},
			setPayment(name, order) {
				console.log('*-*-*')
				uni.requestPayment({
					provider: name,
					orderInfo: order, //微信、支付宝订单数据
					success: function(res) {
						console.log(res)
						uni.hideLoading();
						uni.showLoading({
							title: '支付成功'
						});
					},
					fail: function(err) {
						console.log(err)
						uni.hideLoading();
					},
					complete() {
						uni.hideLoading();
					}
				});
			},
			selectWay1: function(item) {
				this.opentype = item.id;
			},
			// 提现
			cashMoney() {
				let that = this
				if (!that.moneyNum) {
					uni.showToast({
						icon: 'none',
						title: '请输入提现金额'
					})
					return
				}
				// console.log(that.moneyNum,Number(that.moneyNum)>= Number(that.minMoney))
				if (Number(that.moneyNum) < Number(that.minMoney)) {
					uni.showToast({
						icon: 'none',
						title: '提现金额不能少于' + that.minMoney + '元'
					})
					return
				}

				if (that.moneyNum > that.money * 1) {
					uni.showToast({
						icon: 'none',
						title: '您的余额不足'
					})
					return
				}
				// if (that.moneyNum*1+that.charge*that.moneyNum > that.money*1) {
				// 	uni.showToast({
				// 		icon: 'none',
				// 		title: '您的手续费不足'
				// 	})
				// 	return
				// }
				if (that.opentype == 1) { //支付宝提现
					let zhiFuBao = uni.getStorageSync('zhiFuBao')
					let zhiFuBaoName = uni.getStorageSync('zhiFuBaoName')

					if (!zhiFuBao && !zhiFuBaoName) {
						uni.navigateTo({
							url: '/my/wallet/zhifubao'
						})
						return
					}
					that.sp = (that.moneyNum * that.charge).toFixed(2)
					uni.showModal({
						title: '提示',
						content: '本次提现' + that.moneyNum + '元，服务费' + that.sp + '元，是否确认提现？',
						success: function(res) {
							if (res.confirm) {
								that.$Request.get("/app/cash/cashMoney", {
									money: that.moneyNum,
									classify: '1',
									userType: 1
								}).then(res => {
									if (res.code == 0) {
										uni.showToast({
											icon: 'none',
											title: res.msg
										})
										that.moneyNum = null
									} else {
										uni.showToast({
											icon: 'none',
											title: res.msg
										})
									}
									that.getMoney()
								});
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				} else if (that.opentype == 2) {
					if (that.WxTXFangShi == 2) {
						if (that.wxImg) {
							that.sp = (that.moneyNum * that.charge).toFixed(2)
							uni.showModal({
								title: "提现申请提示",
								content: '本次提现' + that.moneyNum + '元，服务费' + that.sp + '元，是否确认提现？',
								success: (e) => {
									if (e.confirm) {
										that.$queue.showLoading("提现中...");
										that.$Request.get("/app/cash/cashMoney", {
											money: that.moneyNum,
											classify: '2',
											userType: 1
										}).then(res => {
											uni.hideLoading();
											if (res.code == 0) {
												uni.showToast({
													icon: 'none',
													title: res.msg
												})
												that.moneyNum = null
											} else {
												uni.showToast({
													icon: 'none',
													title: res.msg
												})
											}
											that.getMoney()
										});
									}
								}
							});
						} else {
							that.show = true;
						}
					} else {
						that.$queue.showLoading("提现中...");
						that.$Request.get("/app/cash/cashMoney", {
							money: that.moneyNum,
							classify: '2',
							userType: 1
						}).then(res => {
							uni.hideLoading();
							if (res.code == 0) {
								uni.showToast({
									icon: 'none',
									title: res.msg
								})
								that.moneyNum = null
							} else {
								uni.showToast({
									icon: 'none',
									title: res.msg
								})
							}
							that.getMoney()
						});
					}
				}
			},
			weixin() {
				let that = this
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: (res) => {
						that.$queue.showLoading("上传中...");
						for (let i = 0; i < 1; i++) {
							uni.uploadFile({ // 上传接口
								url: that.config("APIHOST1") + '/alioss/upload', //真实的接口地址
								// url: 'https://tcwm.xianmaxiong.com/sqx_fast/alioss/upload', //真实的接口地址
								filePath: res.tempFilePaths[i],
								name: 'file',
								success: (uploadFileRes) => {
									// let wxImg = JSON.parse(uploadFileRes.data).data
									// let userId = that.$queue.getData('userId');
									let data = {
										wxImg: JSON.parse(uploadFileRes.data).data
									}
									that.$Request.postJson('/app/user/updateUser',
										data).then(
										res => {
											if (res.code == 0) {
												that.getUserInfo()
												setTimeout(function() {
													that.$queue.showToast('上传成功')
												}, 1000)
												that.getUserInfo()
												that.show = false
											}
										});
									uni.hideLoading();

								}
							});
						}

					}
				});
			},
			config: function(name) {
				var info = null;
				if (name) {
					var name2 = name.split("."); //字符分割
					if (name2.length > 1) {
						info = configdata[name2[0]][name2[1]] || null;
					} else {
						info = configdata[name] || null;
					}
					if (info == null) {
						let web_config = cache.get("web_config");
						if (web_config) {
							if (name2.length > 1) {
								info = web_config[name2[0]][name2[1]] || null;
							} else {
								info = web_config[name] || null;
							}
						}
					}
				}
				return info;
			}
		}
	}
</script>

<style>
	page {
		background-color: #F7F7F7;
	}

	.bg {
		background-color: #FFFFFF;
	}

	.bgCol2 {
		color: #557EFD;
	}

	.active {
		border: 1px solid #557EFD !important;
		color: #557EFD !important;
	}

	.title_btn {
		height: 78upx;
		line-height: 78upx;
		/* background: #f7f7f7; */
	}

	.btn {
		width: 100%;
		height: 88upx;
		background: #557EFD;
		border-radius: 44upx;
		text-align: center;
		line-height: 88upx;
		margin-top: 40upx;
		font-size: 28upx;
		color: #FFF;
	}
</style>